//
//  MineListVC.m
//  ChangChat
//
//  Created by Cocoa on 2019/8/20.
//  Copyright © 2019 yibai. All rights reserved.
//

#import "MineListVC.h"
#import "MineHeadView.h"
#import "YBContentModel.h"
#import "EVCPopInputView.h"
#import "ZXConfirmButton.h"
#import <BRDatePickerView.h>
#import "ChooseLocationView.h"
#import "CitiesDataTool.h"
#import "AppDelegate.h"
#import "YBApiManager+Mine.h"
#import "YBApiManager+Global.h"
#import <TZImagePickerController/TZImagePickerController.h>

@interface MineListVC ()<UIImagePickerControllerDelegate,UINavigationControllerDelegate>
@property (nonatomic, strong) UIImagePickerController * currentPickerController;

@property (nonatomic, strong) MineHeadView *userView;

@property (nonatomic, strong) UIView *chooseLocationContentView;
@property (nonatomic, strong) ChooseLocationView *chooseLocationView;
@property (nonatomic, strong) AddressItem *addressItem;
@end

@implementation MineListVC
- (void)loadView {
    UIView *view = [[UIView alloc] initWithFrame:ScreenBounds];
    view.backgroundColor = UIColor.whiteColor;
    self.view = view;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupUI];
    [self requestMyInfo];
    [self setupDatasource];
    [[CitiesDataTool sharedManager] requestGetData];
    self.title = @"我的";
    
    @weakify(self);
    [[RACObserve(kUsermanager, me.avatar) takeUntil:self.rac_willDeallocSignal] subscribeNext:^(id  _Nullable x) {
        @strongify(self);
        [self.userView.iconImgView sd_setImageWithURL:kUsermanager.me.avatar.toURL placeholderImage:UIImage.k_imgName(@"placeholder_user")];
    }];
    [[RACObserve(kUsermanager, me.username) takeUntil:self.rac_willDeallocSignal] subscribeNext:^(id  _Nullable x) {
        @strongify(self);
        self.userView.nicknameLabel.text = kUsermanager.me.username;
    }];
}

- (void)setupUI {
    UIView *topView = [UIView new];
    topView.backgroundColor = UIColor.clearColor;
    UILabel *titleLabel = [UILabel k_labelWithText:@"我的" fontSize:17 textColor:UIColor.whiteColor];
    [topView addSubview:titleLabel];
    [self.view addSubview:topView];
    [topView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_offset(0);
        if (@available(iOS 11.0, *)) {
            make.top.equalTo(self.view.mas_safeAreaLayoutGuideTop);
        } else {
            make.top.equalTo(self.view).offset(20);
        }
        make.height.mas_equalTo(35);
    }];
    [titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.equalTo(topView);
    }];
    
    self.fd_prefersNavigationBarHidden = YES;
    self.automaticallyAdjustsScrollViewInsets = NO;
    if (@available(iOS 11.0, *)) {
        self.tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    } else {
    }
    
    self.userView = [[MineHeadView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, 200)];
    self.tableView.tableHeaderView = self.userView;
    [self.userView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.mas_equalTo(ScreenWidth);
    }];
    @weakify(self);
    [[self.userView.editIconBtn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
        @strongify(self);
        [self didClickUploadBtnAction];
    }];
    [[self.userView.editNicknameBtn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
        EVCPopInputView *popView = [EVCPopInputView popInputViewWithTitle:@"修改昵称" subTitle:nil placehold:@"请输入2~4位平台昵称" preset:kUsermanager.me.username];
        [popView show];
        popView.limitTextNum = 4;
        popView.isNeedLimitTextContent = YES;
        [popView clickButtonAction:^(NSInteger index, NSString *content) {
            if (index == 1) {
                @strongify(self);
                [self changeNickNameWithNewValue:content];
            }
        }];
    }];
    
    [self.tableView layoutIfNeeded];
    self.tableView.tableHeaderView = self.userView;
    
    [self.tableView customRegisterClassWithName:@"MineCell"];
}

- (void)requestMyInfo {
    @weakify(self);
    [[[YBApiManager shareManager] getMyInfo] subscribeNext:^(id  _Nullable x) {
        NSDictionary *dataDic = [x objectForKey:@"data"];
        [kUsermanager saveUserWithInfo:dataDic];
        @strongify(self);
        [self setupDatasource];
    }];
}
- (void)setupDatasource {
    
    self.userView.mobileLabel.text = [NSString stringWithFormat:@"ID: %@",kUsermanager.me.ID];
    self.userView.qqLabel.hidden = NO;
    self.userView.qqLabel.text = [NSString stringWithFormat:@"QQ: %@", kUsermanager.me.QQ?:@""];
    NSArray *dataArr = @[
                         @{@"title": @"性别",
                           @"rightText": kUsermanager.me.gender?:@"",
                           @"icon": @"arrow_right",
                           @"vc": @""
                           },
                         @{@"title": @"生日",
                           @"rightText": kUsermanager.me.birthday?:@"",
                           @"icon": @"arrow_right",
                           @"vc": @""
                           },
                         @{@"title": @"地区",
                           @"rightText": kUsermanager.me.region?:@"",
                           @"icon": @"mine_addr",
                           @"vc": @""
                           },
                         @{@"title": @"个人签名",
                           @"rightText": kUsermanager.me.bio?:@"",
                           @"icon": @"arrow_right",
                           @"vc": @""
                           },
                         @{@"title": @"二维码",
                           @"rightText": @"",
                           @"icon": @"arrow_right",
                           @"vc": @""
                           },
                         @{@"title": @"设置",
                           @"rightText": @"",
                           @"icon": @"arrow_right",
                           @"vc": @""
                           }
                         ];
    
    self.dataSource = [YBContentModel mj_objectArrayWithKeyValuesArray:dataArr];
    for (YBContentModel *obj in self.dataSource) {
        obj.cellId = @"MineCell";
    }
    [self.tableView reloadData];
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    YBContentModel *model = [self.dataSource objectAtIndex:indexPath.row];
    
    if ([model.title isEqualToString:@"个人签名"] == YES) {
        EVCPopInputView *popView = [EVCPopInputView popInputViewWithTitle:@"设置个人签名" subTitle:nil placehold:@"请输入个人签名" preset:model.rightText];
        [popView show];
        [popView clickButtonAction:^(NSInteger index, NSString *content) {
            if (index == 1) {
                [self changeSignWith:model newValue:content];
            }
        }];
        popView.limitTextNum = 30;
    } else if ([model.title isEqualToString:@"性别"] == YES) {
        [LBXAlertAction showActionSheetWithTitle:@"选择性别" message:nil cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitle:@[@"男", @"女"] chooseBlock:^(NSInteger buttonIdx) {
            if (buttonIdx == 1) {//男
                [self changeSexWith:model newValue:@"男"];
            } else if (buttonIdx == 2) {// 女
                [self changeSexWith:model newValue:@"女"];
            }
        }];
    } else if ([model.title isEqualToString:@"生日"] == YES) {
        [self showSelectBirthdayWithModel:model];
    } else if ([model.title isEqualToString:@"地区"] == YES) {
        [self showChooseLocationViewWithModel:model];
    } else if ([model.title isEqualToString:@"二维码"] == YES) {
        [self.navigationController pushViewController:[NSClassFromString(@"MyQRCodeVC") new] animated:YES];
    }  else if ([model.title isEqualToString:@"设置"] == YES) {
        [self.navigationController pushViewController:[NSClassFromString(@"SettingVC") new] animated:YES];
    } else if ([model.title isEqualToString:@"退出登录"] == YES) {
        
        
        
        
        
    }
}
- (void)changeSexWith:(YBContentModel *)model newValue:(NSString *)newValue {
    
    NSString *sex = [newValue isEqualToString:@"男"] == YES ? @"1" : @"0";
    [self changeMyInfoWithAvatar:nil username:nil nickname:nil bio:nil gender:sex birthday:nil region:nil complete:^{
        model.rightText = newValue;
        [self.tableView reloadData];
    }];
}
- (void)changeSignWith:(YBContentModel *)model newValue:(NSString *)newValue {
    [self changeMyInfoWithAvatar:nil username:nil nickname:nil bio:newValue gender:nil birthday:nil region:nil complete:^{
        model.rightText = newValue;
        [self.tableView reloadData];
    }];
}
- (void)changeRegionWith:(YBContentModel *)model newValue:(NSString *)newValue {
    [self changeMyInfoWithAvatar:nil username:nil nickname:nil bio:nil gender:nil birthday:nil region:newValue complete:^{
        model.rightText = newValue;
        [self.tableView reloadData];
    }];
}
- (void)changeBirthdayWithModel:(YBContentModel *)model newValue:(NSString *)newValue {
    [self changeMyInfoWithAvatar:nil username:nil nickname:nil bio:nil gender:nil birthday:newValue region:nil complete:^{
        model.rightText = newValue;
        [self.tableView reloadData];
    }];
}
- (void)changeNickNameWithNewValue:(NSString *)newValue {
    [self changeMyInfoWithAvatar:nil username:newValue nickname:nil bio:nil gender:nil birthday:nil region:nil complete:^{
        kUsermanager.me.username = newValue;
        self.userView.nicknameLabel.text = newValue;
        [[NSNotificationCenter defaultCenter] postNotificationName:notification_Friend_Info_Changed object:kUsermanager.me];
    }];
}
- (void)changeAvatarWithUrl:(NSString *)newValue img:(UIImage *)img {
    [self changeMyInfoWithAvatar:newValue username:nil nickname:nil bio:nil gender:nil birthday:nil region:nil complete:^{
        kUsermanager.me.avatar = newValue;
        self.userView.iconImgView.image = img;
        [[NSNotificationCenter defaultCenter] postNotificationName:notification_Friend_Info_Changed object:kUsermanager.me];
    }];
}

- (void)showSelectBirthdayWithModel:(YBContentModel *)model {
    [BRDatePickerView showDatePickerWithTitle:@"开始时间" dateType:BRDatePickerModeYMD defaultSelValue:nil resultBlock:^(NSString *selectValue) {
        NSLog(@"selectValue  = %@", selectValue);
        [self changeBirthdayWithModel:model newValue:selectValue];
    }];
}

#pragma mark - 修改个人信息
- (void)changeMyInfoWithAvatar:(NSString *)avatar username:(NSString *)username nickname:(NSString *)nickname bio:(NSString *)bio gender:(NSString *)gender birthday:(NSString *)birthday region:(NSString *)region complete:(void(^)(void))complete {
    [MBProgressHUD hideHUD];
    [MBProgressHUD showTipMessageInView:@"修改成功" timer:1.0];
    [[YBApiManager.shareManager changeMyInfoWithAvatar:avatar username:username nickname:nickname bio:bio gender:gender birthday:birthday region:region] subscribeNext:^(id  _Nullable x) {
        if (complete) {
            complete();
        }
    } error:^(NSError * _Nullable error) {
        [MBProgressHUD hideHUD];
        if ([error isServerError]) {
            [MBProgressHUD showTipMessageInView:error.localizedDescription timer:1.0f];
        } else {
            [MBProgressHUD showTipMessageInView:@"网络错误，请重试" timer:1.0f];
        }
    }];
}

#pragma mark - addr 三级联动

- (void)showChooseLocationViewWithModel:(YBContentModel *)model {
    [kWindow addSubview:self.chooseLocationContentView];
    self.chooseLocationView.hidden = NO;
    [self.chooseLocationContentView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(kWindow);
    }];
    @weakify(self);
    _chooseLocationView.chooseFinish = ^{
        @strongify(self);
        self.addressItem = self->_chooseLocationView.lastItem;
//        model.rightText = self->_chooseLocationView.address;
//        [self.tableView reloadData];
        [self changeRegionWith:model newValue:self->_chooseLocationView.address];
        [self hideChooseLocationView];
    };
}
- (void)hideChooseLocationView {
    [self.chooseLocationContentView removeFromSuperview];
    self.chooseLocationContentView = nil;
    self.chooseLocationView = nil;
}

- (UIView *)chooseLocationContentView {
    if (_chooseLocationContentView == nil) {
        _chooseLocationContentView = [UIView new];
        //        [self.view addSubview:_chooseLocationContentView];
        //        [_chooseLocationContentView mas_makeConstraints:^(MASConstraintMaker *make) {
        //            make.edges.equalTo(self.view);
        //        }];
        _chooseLocationContentView.backgroundColor = [UIColor colorWithWhite:0 alpha:0.2];
        [_chooseLocationContentView addSubview:self.chooseLocationView];
        [self.chooseLocationView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.bottom.mas_equalTo(0);
            make.height.mas_equalTo(350);
        }];
        
        UIView *topView = [UIView new];
        topView.backgroundColor = UIColor.clearColor;
        [_chooseLocationContentView addSubview:topView];
        [topView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.left.right.mas_equalTo(0);
            make.bottom.equalTo(self.chooseLocationView.mas_top);
        }];
        UITapGestureRecognizer *tapG = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hideChooseLocationView)];
        [topView addGestureRecognizer:tapG];
    }
    return _chooseLocationContentView;
}
- (ChooseLocationView *)chooseLocationView {
    if (_chooseLocationView == nil) {
        _chooseLocationView = [[ChooseLocationView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, 350) type:0];
        @weakify(self);
        
        
        _chooseLocationView.cancelAction = ^{
            @strongify(self);
            [self hideChooseLocationView];
        };
    }
    return _chooseLocationView;
}


#pragma mark - 上传图片
- (void)didClickUploadBtnAction {
    [self.view endEditing:YES];
    
    [LBXAlertAction showActionSheetWithTitle:@"选择图片" message:nil cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitle:@[@"拍照",@"相册"] chooseBlock:^(NSInteger buttonIdx) {
        
        if (buttonIdx == 1) {
            [self obtainPhotoByCamera];
        } else if (buttonIdx == 2) {
            [self obtainPhotoFromAlbum];
        }
    }];
}

//打开相机
- (void)obtainPhotoByCamera
{
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
    {
        UIImagePickerController * imagePickerController = [[UIImagePickerController alloc] init] ;
        imagePickerController.sourceType = UIImagePickerControllerSourceTypeCamera ;
        imagePickerController.delegate = self;
        imagePickerController.navigationBar.translucent = NO;
        imagePickerController.showsCameraControls=YES;
        imagePickerController.navigationBar.tintColor = [UIColor whiteColor];
        imagePickerController.modalPresentationStyle = UIModalPresentationOverCurrentContext;
        _currentPickerController = imagePickerController;
        
        kAppDelegate.window.rootViewController.definesPresentationContext = YES;
        [kAppDelegate.window.rootViewController presentViewController:_currentPickerController  animated:YES completion:nil];
    }
}
#pragma mark - UIImagePickerControllerDelegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
{
    [picker dismissViewControllerAnimated:YES completion:nil];
    
    NSString *type = [info objectForKey:UIImagePickerControllerMediaType];
    if ([type isEqualToString:@"public.image"]) {
        TZImagePickerController *tzImagePickerVc = [[TZImagePickerController alloc] initWithMaxImagesCount:1 delegate:nil];
        
        [tzImagePickerVc showProgressHUD];
        UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
        
        // save photo and get asset / 保存图片，获取到asset
        [[TZImageManager manager] savePhotoWithImage:image location:nil completion:^(PHAsset *asset, NSError *error) {
            if (error) {
                [tzImagePickerVc hideProgressHUD];
                NSLog(@"图片保存失败 %@",error);
            } else {
                [[TZImageManager manager] getCameraRollAlbum:NO allowPickingImage:YES needFetchAssets:NO completion:^(TZAlbumModel *model) {
                    [[TZImageManager manager] getAssetsFromFetchResult:model.result allowPickingVideo:NO allowPickingImage:YES completion:^(NSArray<TZAssetModel *> *models) {
                        [tzImagePickerVc hideProgressHUD];
                        TZAssetModel *assetModel = [models firstObject];
                        if (tzImagePickerVc.sortAscendingByModificationDate) {
                            assetModel = [models lastObject];
                        }
                        if (1) { // 允许裁剪,去裁剪
                            TZImagePickerController *imagePicker = [[TZImagePickerController alloc] initCropTypeWithAsset:assetModel.asset photo:image completion:^(UIImage *cropImage, id asset) {
                                [self uploadImage:cropImage];
                            }];
                            imagePicker.needCircleCrop = NO;
                            imagePicker.circleCropRadius = 100;
                            [self presentViewController:imagePicker animated:YES completion:nil];
                        }
                    }];
                }];
            }
        }];
    }
}

//打开相册
- (void)obtainPhotoFromAlbum
{
    TZImagePickerController *tz = [[TZImagePickerController alloc] initWithMaxImagesCount:1 columnNumber:6 delegate:nil];
    tz.allowTakePicture =
    tz.allowPickingOriginalPhoto =
    tz.allowPickingVideo = NO;
    tz.allowCrop = YES;
//    tz.photoPreviewPageDidLayoutSubviewsBlock = ^(UICollectionView *collectionView, UIView *naviBar, UIButton *backButton, UIButton *selectButton, UILabel *indexLabel, UIView *toolBar, UIButton *originalPhotoButton, UILabel *originalPhotoLabel, UIButton *doneButton, UIImageView *numberImageView, UILabel *numberLabel) {
//        naviBar.height = 44;
//        backButton.top = 0;
//        backButton.left = 20;
//        toolBar.height = 44;
//        toolBar.bottom = ScreenHeight;
//        doneButton.right = toolBar.width - 20;
//        doneButton.top = 0;
//    };
//    NSInteger widthHeight = self.view.height - 2 * 44;
//    NSInteger top = (self.view.height - widthHeight) / 2;
//    NSInteger left = self.view.width/2 - widthHeight/2;
//    tz.cropRect = CGRectMake(left, top, widthHeight, widthHeight);
//    // 设置横屏下的裁剪尺寸
//    tz.cropRectLandscape = CGRectMake((self.view.width - widthHeight) / 2, top, widthHeight, widthHeight);
    
    [tz setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isSelectOriginalPhoto) {
        [self uploadImage:photos.firstObject];
    }];
    
    [self presentViewController:tz animated:YES completion:nil];
}

- (void)uploadImage:(UIImage *)image{
    [MBProgressHUD showActivityMessageInView:@"上传中..."];
    @weakify(self);
    
    YBApiManager *newApiM = YBApiManager.shareManager;
    [[newApiM uploadImgWithImage:image] subscribeNext:^(id  _Nullable x) {
        NSString *imgUrlStr = [[x objectForKey:@"data"] objectForKey:@"url"];
        @strongify(self);
        //        self.iconImgView.image = image;
        //        self.imgPath = imgUrlStr;
        [self changeAvatarWithUrl:imgUrlStr img:image];
    } error:^(NSError * _Nullable error) {
        [MBProgressHUD hideHUD];
        if ([error isServerError]) {
            [MBProgressHUD showTipMessageInView:error.localizedDescription timer:1.0f];
        } else {
            [MBProgressHUD showTipMessageInView:@"网络错误，请重试" timer:1.0f];
        }
    }];
}


@end
